#!/usr/bin/perl -w
use strict;


use Device::SerialPort;
use LWP::UserAgent;

my $dev = "/dev/ttyUSB0";
my $ua = LWP::UserAgent->new;
$ua->agent("RedBee/0.1");
my $req = HTTP::Request->new(POST => 'http://www.portabrowse.com/findyourstuff.php');
$req->content_type('application/x-www-form-urlencoded');

# Specify a location where the device configuration will be saved
my $cfg = "redbee.cfg";

my $portobj = new Device::SerialPort($dev) or die "Unable to open port
$dev: $!\n";

$portobj->databits(8);
$portobj->baudrate(9600);
$portobj->parity("none");
$portobj->stopbits(1);
# handshake parameter sets flow control as well
$portobj->handshake("none");

$portobj->save($cfg);

my $STALL=20;
my $timeout=$STALL;

$portobj->read_char_time(0); # don't wait for each char
$portobj->read_const_time(1000); # 1 sec per unfulfilled read call

my $chars = 0;
my $buffer = "";
while($timeout>0)
{
       my($count,$saw)=$portobj->read(255); # read up to 255 chars
       if($count > 0)
       {
               $chars+=$count;
               $buffer.=$saw;
		#$buffer =~ m/.*ACK(.*)$/;
               printf("Saw %s\n",$buffer);
		$req->content("coord=$buffer");
		my $res = $ua->request($req);
		print $res->content;
               $portobj->close();
               last;
       }
       else { $timeout--;}
}

if($timeout==0)
{
       die "waited!\n";
}
